package cn.yiya.shiji.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.google.gson.Gson;

import java.util.ArrayList;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.GoodsDetailActivity;
import cn.yiya.shiji.activity.LoginActivity;
import cn.yiya.shiji.activity.SingleBrandOrderActivity;
import cn.yiya.shiji.adapter.HorRecyclerViewAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MapRequest;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.ActivityInfo;
import cn.yiya.shiji.entity.ActivityListObject;
import cn.yiya.shiji.entity.GoodsIdInfo;
import cn.yiya.shiji.entity.HtmlInfo;
import cn.yiya.shiji.entity.NewGoodsObject;
import cn.yiya.shiji.entity.goodes.NewGoodsItem;
import cn.yiya.shiji.netroid.Netroid;
import cn.yiya.shiji.views.FullyLinearLayoutManager;

/**
 * Created by chenjian on 2015/11/10.
 */
public class BrandsNewestFragment extends BaseFragment {
    private ConvenientBanner convenientBanner;//顶部广告栏控件
    private Handler mHandler;
    public ArrayList<ActivityListObject.ActivityListItem> mActivityLists;
    private int brandId;
    private ArrayList<NewGoodsItem> mPopularLists;
    private ArrayList<NewGoodsItem> mNewestLists;
    private ArrayList<NewGoodsItem> mLowestLists;
    private ArrayList<NewGoodsItem> mDiscountList;
    private RecyclerView mRecyclerViewPop;
    private RecyclerView mRecyclerViewNew;
    private RecyclerView mRecyclerViewLow;
    private RecyclerView mRecyclerViewDiscount;
    private View mView;
    private NestedScrollView nsRoot;
    private boolean isLogin = false;
    private static final int REQUEST_LOGIN = 1001;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler(getActivity().getMainLooper());
        initLoginState();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_brands_newest, container, false);

        initViews();
        initEvents();
        init();

        return mView;
    }

    @Override
    protected void initViews() {
        brandId = ((SingleBrandOrderActivity)getActivity()).brand_id;
        nsRoot = (NestedScrollView)mView.findViewById(R.id.nested_parent);
        convenientBanner = (ConvenientBanner)mView.findViewById(R.id.brands_viewpager);
        convenientBanner.setPageIndicator(new int[]{R.drawable.indictator_normal, R.drawable.indictator_focused});
        convenientBanner.setDividerPadding(6);

        mRecyclerViewPop = (RecyclerView)mView.findViewById(R.id.recycler_work_hot_list);
        mRecyclerViewNew = (RecyclerView)mView.findViewById(R.id.recycler_work_new_list);
        mRecyclerViewLow = (RecyclerView)mView.findViewById(R.id.recycler_work_low_list);
        mRecyclerViewDiscount = (RecyclerView)mView.findViewById(R.id.recycler_work_discount_list);

        initRecyclerView(mRecyclerViewPop);
        initRecyclerView(mRecyclerViewNew);
        initRecyclerView(mRecyclerViewLow);
        initRecyclerView(mRecyclerViewDiscount);
    }

    @Override
    protected void initEvents() {

    }

    @Override
    protected void init() {
        getActivityList();
        getPopularGoods();
        getNewestGoods();
        getLowestGoods();
        getDiscount();
    }

    private void initLoginState() {
        new RetrofitRequest<>(ApiRequest.getApiShiji().isLogin()).handRequest(
                new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            isLogin = true;
                        } else if (msg.isLossLogin()) {
                            isLogin = false;
                        }
                    }
                }
        );
    }

    private void initAdapterEvents(HorRecyclerViewAdapter adapter) {
        adapter.setOnItemClickListener(new HorRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(NewGoodsItem data) {
                gotoGoodsDetail(data);
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        FullyLinearLayoutManager manager = new FullyLinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        manager.setSmoothScrollbarEnabled(true);
        recyclerView.setLayoutManager(manager);
        recyclerView.setNestedScrollingEnabled(false);
//        recyclerView.setHasFixedSize(false);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    // 获取活动列表
    private void getActivityList(){
        convenientBanner.setVisibility(View.GONE);
        new RetrofitRequest<ActivityListObject>(ApiRequest.getApiShiji().getActivityList(String.valueOf(brandId))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    ActivityListObject item = (ActivityListObject) msg.obj;
                    if (item.getList() != null && item.getList().size() > 0) {
                        mActivityLists = item.getList();
                        convenientBanner.setVisibility(View.VISIBLE);
                        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
                            @Override
                            public NetworkImageHolderView createHolder() {
                                return new NetworkImageHolderView();
                            }
                        }, mActivityLists);
                    }
                }
            }
        });
    }

    // 获取最热商品
    private void getPopularGoods() {
        new RetrofitRequest<NewGoodsObject>(ApiRequest.getApiShiji().getHotSingleList(
        MapRequest.setHotSingleList(brandId))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    NewGoodsObject info = (NewGoodsObject) msg.obj;
                    if (info.getGoods() != null && info.getGoods().size() > 0) {
                        mPopularLists = info.getGoods();
                        mRecyclerViewPop.setNestedScrollingEnabled(false);
                        HorRecyclerViewAdapter popGoodsAdapter = new HorRecyclerViewAdapter(getActivity(), mPopularLists, 5);
                        mRecyclerViewPop.setAdapter(popGoodsAdapter);
                        initAdapterEvents(popGoodsAdapter);
                    }
                }
            }
        });
    }

    // 获取最新单品
    private void getNewestGoods() {
        new RetrofitRequest<NewGoodsObject>(ApiRequest.getApiShiji().getNewGoodsList(
        MapRequest.setNewGoodsList(brandId,0))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    NewGoodsObject info = (NewGoodsObject) msg.obj;
                    if (info.getGoods() != null && info.getGoods().size() > 0) {
                        mNewestLists = info.getGoods();
                        mRecyclerViewNew.setNestedScrollingEnabled(false);
                        HorRecyclerViewAdapter newestGoodsAdapter = new HorRecyclerViewAdapter(getActivity(), mNewestLists, 1);
                        mRecyclerViewNew.setAdapter(newestGoodsAdapter);
                        initAdapterEvents(newestGoodsAdapter);
//                        mRecyclerViewNew.setAdapter(new HorRecyclerViewAdapter(getActivity(), mNewestLists, 1));
                    }
                }
            }
        });
    }

    // 获取最低价商品
    private void getLowestGoods() {
        new RetrofitRequest<NewGoodsObject>(ApiRequest.getApiShiji().getCheapGoods(
        MapRequest.setHotSingleList(brandId))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    NewGoodsObject info = (NewGoodsObject) msg.obj;
                    if (info.getGoods() != null && info.getGoods().size() > 0) {
                        mLowestLists = info.getGoods();
                        mRecyclerViewLow.setNestedScrollingEnabled(false);
                        HorRecyclerViewAdapter lowestGoodsAdapter = new HorRecyclerViewAdapter(getActivity(), mLowestLists, 3);
                        mRecyclerViewLow.setAdapter(lowestGoodsAdapter);
                        initAdapterEvents(lowestGoodsAdapter);
//                        mRecyclerViewLow.setAdapter(new HorRecyclerViewAdapter(getActivity(), mLowestLists, 3));
                    }
                }
            }
        });
    }

    // 获取最低折扣商品
    private void getDiscount() {
        new RetrofitRequest<NewGoodsObject>(ApiRequest.getApiShiji().getDiscountGoods(
                MapRequest.setHotSingleList(brandId))).handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    NewGoodsObject info = (NewGoodsObject) msg.obj;
                    if (info.getGoods() != null && info.getGoods().size() > 0) {
                        mDiscountList = info.getGoods();
                        mRecyclerViewDiscount.setNestedScrollingEnabled(false);
                        HorRecyclerViewAdapter discountGoodsAdapter = new HorRecyclerViewAdapter(getActivity(), mDiscountList, 4);
                        mRecyclerViewDiscount.setAdapter(discountGoodsAdapter);
                        initAdapterEvents(discountGoodsAdapter);
//                        mRecyclerViewDiscount.setAdapter(new HorRecyclerViewAdapter(getActivity(), mDiscountList, 4));
                    }
                }
            }
        });
    }

    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        convenientBanner.startTurning(4000);//此值不能小于1200（即ViewPagerScroller的mScrollDuration的值），否则最后一页翻页效果会出问题。如果硬要兼容1200以下，那么请修改ViewPagerScroller的mScrollDuration的值，不过修改后，3d效果就没那么明显了。
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        convenientBanner.stopTurning();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == REQUEST_LOGIN){
                isLogin = true;
            }
        }
    }

    private void gotoGoodsDetail(final NewGoodsItem info){
        if(isEffectClick()) {
            GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
            goodsIdInfo.setGoodsId(info.getId());
            Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
            intent.putExtra("data", new Gson().toJson(goodsIdInfo));
            startActivity(intent);
//            if (isLogin) {
//                GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
//                goodsIdInfo.setGoodsId(info.getId());
//                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
//                intent.putExtra("data", new Gson().toJson(goodsIdInfo));
//                startActivity(intent);
//            } else {
//                Intent intent = new Intent(getActivity(), LoginActivity.class);
//                startActivityForResult(intent, REQUEST_LOGIN);
//                getActivity().overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
//            }
        }
    }

    class NetworkImageHolderView implements Holder<ActivityListObject.ActivityListItem> {
        private ImageView imageView;
        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(final Context context, final int position, final ActivityListObject.ActivityListItem data) {
            imageView.setImageResource(R.drawable.user_dafault);
            Netroid.displayImage(data.getCover(), imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HtmlInfo htmlInfo = new HtmlInfo();
                    ActivityInfo activityInfo = new ActivityInfo();
                    activityInfo.setActivityId(data.getId());
                    activityInfo.setActivityType(1);
                    htmlInfo.setData(activityInfo);
                    htmlInfo.setType(4);
                    htmlInfo.setUrl("/home/homeIssue.html");
                    Intent intent = new Intent(context, GoodsDetailActivity.class);
                    intent.putExtra("data", new Gson().toJson(htmlInfo));
                    context.startActivity(intent);
                }
            });
        }
    }
}

